import React, { useEffect, useState } from 'react';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';

import { newActionRuleApi } from '@/api/rulesWarningConfig';
import { equipmentProductListApi, equipmentProductDetailApi } from '@/api/equipmentProductApi';
import { deviceManagerListApi } from '@/api/deviceManagerApi';

interface ActionRule {
  id: string;
  actionTypeName: string;
  sms?: string;
  email?: string;
  productCode?: string;
  deviceCodes?: string[];
  serviceType?: string; // 服务类型
  services?: string; // 具体服务
  serviceParams?: Record<string, unknown>;
  http?: {
    url?: string;
    method?: string;
    header?: string;
  };
}

interface ServiceOption {
  label: string;
  value: string;
  params?: ServiceParam[];
}

interface ServiceParam {
  identifier: string;
  name?: string;
  dataType?: {
    specs?: {
      unit?: string;
    };
  };
}

interface EditActionRulesDrawerProps {
  open: boolean;
  onClose: () => void;
  ruleId?: string;
  initialData?: {
    actionExecutionMode?: string;
    actions?: Array<{
      actionTypeName?: string;
      orderIndex?: number;
      param?: unknown;
    }>;
  };
  onSuccess?: () => void;
}

const actionTypeOptions = [
  // { label: '告警中心', value: 'alarm' },
  // { label: '短信通知', value: 'sms' },
  // { label: '邮件通知', value: 'email' },
  // { label: '第三方推送', value: 'http' },
  { label: '指令下发', value: 'cmddown' },
];

const EditActionRulesDrawer: React.FC<EditActionRulesDrawerProps> = ({
  open,
  onClose,
  ruleId,
  initialData,
  onSuccess,
}) => {
  const [form] = AForm.useForm();
  const [loading, setLoading] = useState(false);
  const [productOptions, setProductOptions] = useState<
    Array<{ label: string; value: string; id: number }>
  >([]);
  const [deviceOptions, setDeviceOptions] = useState<
    Record<string, Array<{ label: string; value: string }>>
  >({});
  const [serviceOptions, setServiceOptions] = useState<Record<string, ServiceOption[]>>({});
  const [serviceParams, setServiceParams] = useState<Record<string, ServiceParam[]>>({});
  const [actionRules, setActionRules] = useState<ActionRule[]>([
    {
      id: '1',
      actionTypeName: 'alarm',
    },
  ]);
  // 用于缓存每个动作的历史数据，避免切换动作类型时丢失数据
  const [actionDataCache, setActionDataCache] = useState<Record<string, Partial<ActionRule>>>({});

  // 获取产品列表
  const fetchProductList = async () => {
    try {
      const res = await equipmentProductListApi({
        page: 1,
        pageSize: 100,
      });
      if (res.success && res.data?.records) {
        const options = res.data.records.map((item: Record<string, unknown>) => ({
          label: item.productName as string,
          value: item.code as string,
          id: item.id as number,
        }));
        setProductOptions(options);
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
    }
  };

  // 获取设备列表
  const fetchDeviceList = async (productCode: string) => {
    if (deviceOptions[productCode]) {
      console.log('Device options already exist for:', productCode);
      return;
    }

    try {
      const res = await deviceManagerListApi({
        page: 1,
        pageSize: 100,
        productCode,
      });
      if (res.success && res.data?.records) {
        const options = res.data.records.map((item: Record<string, unknown>) => ({
          label: (item.deviceName as string) || (item.code as string),
          value: item.code as string,
        }));
        setDeviceOptions(prev => ({
          ...prev,
          [productCode]: options,
        }));
      }
    } catch (error) {
      console.error('获取设备列表失败:', error);
    }
  };

  // 获取产品详情和服务列表
  const fetchProductDetail = async (productCode: string) => {
    console.log('fetchProductDetail called:', productCode);
    if (serviceOptions[productCode]) {
      console.log('Service options already exist for:', productCode);
      return;
    }

    try {
      // 根据productCode找到对应的产品ID
      const product = productOptions.find(p => p.value === productCode);
      if (!product) {
        console.error('Product not found for code:', productCode);
        return;
      }
      const res = await equipmentProductDetailApi({ id: product.id.toString() });
      if (res.success && res.data?.metaData) {
        // 解析metaData中的services
        const metaData = JSON.parse(res.data.metaData as string) as Record<string, unknown>;
        if (metaData.services && Array.isArray(metaData.services)) {
          const options: ServiceOption[] = metaData.services.map(
            (service: Record<string, unknown>) => ({
              label: (service.name as string) || (service.identifier as string),
              value: service.identifier as string,
              params: (service.inputData as ServiceParam[]) || [],
            })
          );
          setServiceOptions(prev => ({
            ...prev,
            [productCode]: options,
          }));
        }
      }
    } catch (error) {
      console.error('获取产品详情失败:', error);
    }
  };

  // 获取服务参数
  const fetchServiceParams = (productCode: string, serviceId: string) => {
    const services = serviceOptions[productCode] || [];
    const service = services.find(s => s.value === serviceId);
    if (service && service.params) {
      // 处理参数，为每个参数添加默认值
      const processedParams: ServiceParam[] = service.params.map((param: ServiceParam) => ({
        identifier: param.identifier,
        name: param.name,
        dataType: param.dataType,
      }));
      setServiceParams(prev => ({
        ...prev,
        [`${productCode}_${serviceId}`]: processedParams,
      }));
    }
  };

  // 初始化数据
  useEffect(() => {
    if (open) {
      fetchProductList();
      if (initialData) {
        form.setFieldsValue({
          // actionExecutionMode: initialData.actionExecutionMode || 'parallel',
          actionExecutionMode: 'parallel',
        });

        // 转换现有动作数据
        if (initialData.actions && initialData.actions.length > 0) {
          const convertedActions = initialData.actions.map((action, index) => {
            const baseAction: ActionRule = {
              id: String(index + 1),
              actionTypeName: action.actionTypeName || 'alarm',
            };

            // 根据动作类型解析参数
            if (action.param) {
              let param: Record<string, unknown>;
              try {
                // 尝试解析JSON字符串参数（与旧代码保持一致）
                param = typeof action.param === 'string' ? JSON.parse(action.param) : action.param;
              } catch {
                param = action.param as Record<string, unknown>;
              }

              switch (action.actionTypeName) {
                case 'sms':
                  baseAction.sms = (param.smsAddress as string[])?.join(',') || '';
                  break;
                case 'email':
                  baseAction.email = (param.emailAddress as string[])?.join(',') || '';
                  break;
                case 'http':
                  baseAction.http = {
                    url: (param.url as string) || '',
                    method: (param.method as string) || '',
                    header: (param.header as string) || '',
                  };
                  break;
                case 'cmddown':
                  baseAction.productCode = (param.productCode as string) || '';
                  baseAction.deviceCodes = (param.deviceCodes as string[]) || [];
                  baseAction.services = (param.identifier as string) || '';
                  baseAction.serviceParams = (param.inputParam as Record<string, unknown>) || {};

                  // 异步加载设备数据
                  setTimeout(async () => {
                    if (baseAction.productCode) {
                      await fetchDeviceList(baseAction.productCode);
                    }
                  }, 0);
                  break;
              }
            }

            return baseAction;
          });
          setActionRules(convertedActions);
        }
      }
    }
  }, [open, initialData, form]);

  // 监听productOptions变化，加载产品详情
  useEffect(() => {
    if (productOptions.length > 0 && initialData?.actions) {
      initialData.actions.forEach((action, index) => {
        if (action.actionTypeName === 'cmddown' && action.param) {
          let param: Record<string, unknown>;
          try {
            param = typeof action.param === 'string' ? JSON.parse(action.param) : action.param;
          } catch {
            param = action.param as Record<string, unknown>;
          }

          const productCode = param.productCode as string;

          if (productCode) {
            // 确保产品存在后再获取产品详情
            const product = productOptions.find(p => p.value === productCode);
            if (product) {
              fetchProductDetail(productCode);
            } else {
              console.warn(
                'Product not found for code:',
                productCode,
                'Available products:',
                productOptions
              );
            }
          }
        }
      });
    }
  }, [productOptions, initialData]);

  // 监听serviceOptions变化，初始化服务参数
  useEffect(() => {
    if (Object.keys(serviceOptions).length > 0 && initialData?.actions) {
      initialData.actions.forEach((action, index) => {
        if (action.actionTypeName === 'cmddown' && action.param) {
          let param: Record<string, unknown>;
          try {
            param = typeof action.param === 'string' ? JSON.parse(action.param) : action.param;
          } catch {
            param = action.param as Record<string, unknown>;
          }

          const productCode = param.productCode as string;
          const serviceId = param.identifier as string;
          const inputParam = param.inputParam as Record<string, unknown>;

          if (productCode && serviceId && serviceOptions[productCode]) {
            // 获取服务参数
            fetchServiceParams(productCode, serviceId);

            // 设置参数值
            setTimeout(() => {
              const paramKey = `${productCode}_${serviceId}`;
              const currentParams = serviceParams[paramKey];
              if (currentParams && inputParam) {
                const updatedParams = currentParams.map((p: ServiceParam) => ({
                  ...p,
                  value: inputParam[p.identifier] || '',
                }));
                setServiceParams(prev => ({
                  ...prev,
                  [paramKey]: updatedParams,
                }));
              }
            }, 100);
          }
        }
      });
    }
  }, [serviceOptions, initialData]);

  // 添加动作规则
  const addActionRule = () => {
    const newAction: ActionRule = {
      id: String(Date.now()),
      actionTypeName: 'alarm',
    };
    setActionRules([...actionRules, newAction]);
  };

  // 删除动作规则
  const deleteActionRule = (actionId: string) => {
    if (actionRules.length <= 1) {
      window.$message.warning('至少需要保留一个动作');
      return;
    }
    setActionRules(actionRules.filter(action => action.id !== actionId));
  };

  // 更新动作规则
  const updateActionRule = (actionId: string, field: string, value: unknown) => {
    setActionRules(
      actionRules.map(action => {
        if (action.id === actionId) {
          const updatedAction = { ...action, [field]: value };

          // 当动作类型改变时，保存当前数据到缓存并尝试恢复目标类型的缓存数据
          if (field === 'actionTypeName') {
            const oldActionType = action.actionTypeName;
            const newActionType = value;

            // 保存当前动作类型的数据到缓存
            if (oldActionType && oldActionType !== 'alarm') {
              const cacheKey = `${actionId}_${oldActionType}`;
              setActionDataCache(prev => ({
                ...prev,
                [cacheKey]: {
                  sms: action.sms,
                  email: action.email,
                  productCode: action.productCode,
                  deviceCodes: action.deviceCodes,
                  serviceType: action.serviceType,
                  services: action.services,
                  serviceParams: action.serviceParams,
                  http: action.http,
                },
              }));
            }

            // 尝试从缓存中恢复新动作类型的数据
            const newCacheKey = `${actionId}_${newActionType}`;
            const cachedData = actionDataCache[newCacheKey];

            if (cachedData && newActionType !== 'alarm') {
              // 恢复缓存的数据
              Object.assign(updatedAction, cachedData);
            } else {
              // 清空相关字段
              updatedAction.sms = '';
              updatedAction.email = '';
              updatedAction.productCode = '';
              updatedAction.deviceCodes = [];
              updatedAction.serviceType = '';
              updatedAction.services = '';
              updatedAction.serviceParams = {};
              updatedAction.http = {
                url: '',
                method: '',
                header: '',
              };
            }
          } else {
            // 非动作类型字段更新时，同时更新缓存
            updateActionCache(actionId, action.actionTypeName, { [field]: value });
          }

          return updatedAction;
        }
        return action;
      })
    );
  };

  // 更新HTTP参数
  const updateHttpParam = (actionId: string, field: string, value: string) => {
    setActionRules(
      actionRules.map(action => {
        if (action.id === actionId) {
          const updatedHttp = {
            ...action.http,
            [field]: value,
          };

          const updatedAction = {
            ...action,
            http: updatedHttp,
          };

          // 同时更新缓存
          updateActionCache(actionId, action.actionTypeName, {
            http: updatedHttp,
          });

          return updatedAction;
        }
        return action;
      })
    );
  };

  // 处理产品选择
  const handleProductChange = (actionId: string, productCode: string) => {
    console.log('handleProductChange called:', { actionId, productCode });

    // 直接更新状态，一次性更新所有相关字段
    setActionRules(prevRules =>
      prevRules.map(action => {
        if (action.id === actionId) {
          const updatedAction = {
            ...action,
            productCode,
            deviceCodes: [],
            serviceType: '',
            services: '',
            serviceParams: {},
          };
          console.log('Updating action:', updatedAction);
          return updatedAction;
        }
        return action;
      })
    );

    // 确保数据存在，如果不存在则获取
    if (!deviceOptions[productCode]) {
      fetchDeviceList(productCode);
    } else {
      console.log('Device options already exist for:', productCode, deviceOptions[productCode]);
    }

    if (!serviceOptions[productCode]) {
      fetchProductDetail(productCode);
    } else {
      console.log('Service options already exist for:', productCode, serviceOptions[productCode]);
    }
  };

  // 处理服务选择
  const handleServiceChange = (actionId: string, serviceId: string) => {
    const action = actionRules.find(a => a.id === actionId);
    if (action?.productCode) {
      // 直接更新状态
      setActionRules(prevRules =>
        prevRules.map(rule => {
          if (rule.id === actionId) {
            const updatedAction = {
              ...rule,
              services: serviceId,
              serviceParams: {},
            };
            return updatedAction;
          }
          return rule;
        })
      );

      // 同时更新缓存
      updateActionCache(actionId, action.actionTypeName, {
        services: serviceId,
        serviceParams: {},
      });

      fetchServiceParams(action.productCode, serviceId);
    }
  };

  // 更新缓存数据
  const updateActionCache = (
    actionId: string,
    actionTypeName: string,
    data: Partial<ActionRule>
  ) => {
    if (actionTypeName && actionTypeName !== 'alarm') {
      const cacheKey = `${actionId}_${actionTypeName}`;
      setActionDataCache(prev => ({
        ...prev,
        [cacheKey]: {
          ...prev[cacheKey],
          ...data,
        },
      }));
    }
  };

  // 更新服务参数
  const updateServiceParam = (actionId: string, paramName: string, value: unknown) => {
    setActionRules(
      actionRules.map(action => {
        if (action.id === actionId) {
          const updatedAction = {
            ...action,
            serviceParams: {
              ...action.serviceParams,
              [paramName]: value,
            },
          };

          // 同时更新缓存
          if (action.actionTypeName && action.actionTypeName !== 'alarm') {
            const cacheKey = `${actionId}_${action.actionTypeName}`;
            setActionDataCache(prev => ({
              ...prev,
              [cacheKey]: {
                ...prev[cacheKey],
                serviceParams: updatedAction.serviceParams,
              },
            }));
          }

          return updatedAction;
        }
        return action;
      })
    );
  };

  // 验证邮箱格式
  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const emails = email.split(',').map(e => e.trim());
    return emails.every(e => emailRegex.test(e));
  };

  // 验证手机号格式
  const validatePhone = (phone: string) => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    const phones = phone.split(',').map(p => p.trim());
    return phones.every(p => phoneRegex.test(p));
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 验证动作规则
      for (const action of actionRules) {
        if (!action.actionTypeName) {
          window.$message.error('请选择执行动作');
          return;
        }

        switch (action.actionTypeName) {
          case 'sms':
            if (!action.sms || !validatePhone(action.sms)) {
              window.$message.error('请输入正确的手机号');
              return;
            }
            break;
          case 'email':
            if (!action.email || !validateEmail(action.email)) {
              window.$message.error('请输入正确的邮箱地址');
              return;
            }
            break;
          case 'http':
            if (!action.http?.url || !action.http?.method) {
              window.$message.error('请完善第三方推送配置');
              return;
            }
            break;
          case 'cmddown':
            if (!action.productCode || !action.deviceCodes?.length || !action.services) {
              window.$message.error('请完善指令下发配置');
              return;
            }
            break;
        }
      }

      setLoading(true);

      const actionReqs = actionRules.map((action, index) => {
        let param: unknown = {};

        switch (action.actionTypeName) {
          case 'alarm':
            param = {};
            break;
          case 'sms':
            param = {
              smsAddress: action.sms?.split(',').map(s => s.trim()) || [],
              templateCode: '001',
            };
            break;
          case 'email':
            param = {
              emailAddress: action.email?.split(',').map(e => e.trim()) || [],
              templateCode: '001',
            };
            break;
          case 'http':
            param = {
              url: action.http?.url || '',
              method: action.http?.method || '',
              header: action.http?.header || '',
            };
            break;
          case 'cmddown': {
            // 获取服务名称
            const serviceName =
              action.productCode && action.services
                ? serviceOptions[action.productCode]?.find(s => s.value === action.services)
                    ?.label || action.services
                : action.services || '';

            param = {
              identifier: action.services || '',
              inputParam: action.serviceParams || {},
              deviceCodes: action.deviceCodes || [],
              productCode: action.productCode || '',
              serviceName,
            };
            break;
          }
        }

        return {
          actionTypeName: action.actionTypeName,
          orderIndex: index,
          param,
        };
      });

      const submitData = {
        actionExecutionMode: values.actionExecutionMode,
        actionReqs,
        ruleConfigureId: ruleId,
      };

      const res = await newActionRuleApi(submitData);
      if (res.success) {
        window.$message.success('编辑动作规则成功');
        onSuccess?.();
        onClose();
      } else {
        window.$message.error(res.errorMsg || '编辑动作规则失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      window.$message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 渲染动作配置表单
  const renderActionForm = (action: ActionRule) => {
    switch (action.actionTypeName) {
      case 'sms':
        return (
          <AForm.Item
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                validator: (_, value) => {
                  if (value && !validatePhone(value)) {
                    return Promise.reject('请输入正确的手机号格式');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <AInput
              placeholder="请输入手机号，多个手机号请使用','分开"
              value={action.sms}
              onChange={e => updateActionRule(action.id, 'sms', e.target.value)}
            />
          </AForm.Item>
        );

      case 'email':
        return (
          <AForm.Item
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              {
                validator: (_, value) => {
                  if (value && !validateEmail(value)) {
                    return Promise.reject('请输入正确的邮箱格式');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <AInput
              placeholder="请输入邮箱地址，多个地址请使用','分开"
              value={action.email}
              onChange={e => updateActionRule(action.id, 'email', e.target.value)}
            />
          </AForm.Item>
        );

      case 'http':
        return (
          <div className="flex space-x-2">
            <AForm.Item
              label="接口地址"
              rules={[{ required: true, message: '请输入接口地址' }]}
              className="flex-1"
            >
              <AInput
                placeholder="请输入接口地址"
                value={action.http?.url}
                onChange={e => updateHttpParam(action.id, 'url', e.target.value)}
              />
            </AForm.Item>
            <AForm.Item label="请求头" className="flex-1">
              <AInput
                placeholder="请输入请求头"
                value={action.http?.header}
                onChange={e => updateHttpParam(action.id, 'header', e.target.value)}
              />
            </AForm.Item>
            <AForm.Item
              label="请求方式"
              rules={[{ required: true, message: '请输入请求方式' }]}
              className="flex-1"
            >
              <AInput
                placeholder="请输入请求方式"
                value={action.http?.method}
                onChange={e => updateHttpParam(action.id, 'method', e.target.value)}
              />
            </AForm.Item>
          </div>
        );

      case 'cmddown': {
        const currentServiceParams =
          action.productCode && action.services
            ? serviceParams[`${action.productCode}_${action.services}`] || []
            : [];

        return (
          <div className="space-y-3">
            <AForm.Item label="产品" rules={[{ required: true, message: '请选择产品' }]}>
              <ASelect
                placeholder="请选择产品"
                value={action.productCode}
                onChange={value => handleProductChange(action.id, value)}
                options={productOptions}
              />
            </AForm.Item>
            <AForm.Item label="设备" rules={[{ required: true, message: '请选择设备' }]}>
              <ASelect
                mode="multiple"
                placeholder="请选择设备"
                value={action.deviceCodes}
                onChange={value => updateActionRule(action.id, 'deviceCodes', value)}
                options={action.productCode ? deviceOptions[action.productCode!] || [] : []}
                disabled={!action.productCode}
              />
            </AForm.Item>
            <AForm.Item label="服务类型" rules={[{ required: true, message: '请选择服务类型' }]}>
              <ASelect
                placeholder="请选择服务类型"
                value={action.services}
                onChange={value => {
                  console.log('Service select onChange:', { actionId: action.id, value });
                  handleServiceChange(action.id, value);
                }}
                options={action.productCode ? serviceOptions[action.productCode!] || [] : []}
                disabled={!action.productCode}
                onOpenChange={open => {
                  if (open && action.productCode) {
                    console.log(
                      'Service options for',
                      action.productCode,
                      ':',
                      serviceOptions[action.productCode]
                    );
                  }
                }}
              />
            </AForm.Item>

            {/* 服务参数配置 */}
            {currentServiceParams.length > 0 && (
              <div className="mt-4">
                <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
                  <div className="text-sm font-medium text-gray-800 mb-3 flex items-center">
                    <span className="w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
                    参数配置
                  </div>
                  <div className="space-y-3">
                    {currentServiceParams.map((param: ServiceParam) => (
                      <div
                        key={param.identifier}
                        className="bg-white rounded-md p-3 border border-gray-100 shadow-sm"
                      >
                        <div className="flex items-center space-x-3">
                          <div className="w-24 flex-shrink-0">
                            <span className="text-sm font-medium text-gray-700">
                              {param.name || param.identifier}
                            </span>
                          </div>
                          <div className="flex-1">
                            <AInput
                              placeholder={`请输入${param.name || param.identifier}`}
                              value={action.serviceParams?.[param.identifier] || ''}
                              onChange={e =>
                                updateServiceParam(action.id, param.identifier, e.target.value)
                              }
                              suffix={
                                param.dataType?.specs?.unit && (
                                  <span className="text-gray-400 text-xs">
                                    {param.dataType.specs.unit}
                                  </span>
                                )
                              }
                              className="border-gray-200 focus:border-blue-400 focus:shadow-sm"
                            />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        );
      }

      default:
        return null;
    }
  };

  return (
    <ADrawer
      title="编辑动作规则"
      width={1000}
      open={open}
      onClose={onClose}
      footer={
        <div className="flex justify-end space-x-2">
          <AButton onClick={onClose}>取消</AButton>
          <AButton type="primary" loading={loading} onClick={handleSubmit}>
            确认
          </AButton>
        </div>
      }
    >
      <AForm form={form} layout="vertical">
        <AForm.Item
          hidden
          label="执行方式"
          name="actionExecutionMode"
          initialValue="parallel"
          rules={[{ required: true, message: '请选择执行方式' }]}
        >
          <ARadio.Group>
            <ARadio value="serial">串行</ARadio>
            <ARadio value="parallel">并行</ARadio>
          </ARadio.Group>
        </AForm.Item>

        <div className="space-y-4">
          {actionRules.map((action, index) => (
            <ACard
              key={action.id}
              title={`执行动作 ${index + 1}`}
              size="small"
              styles={{
                header: {
                  backgroundColor: '#f8f9fa',
                  borderBottom: '1px solid #e9ecef',
                },
              }}
              extra={
                actionRules.length > 1 && (
                  <ATooltip title="删除动作">
                    <AButton
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => deleteActionRule(action.id)}
                    />
                  </ATooltip>
                )
              }
            >
              <AForm.Item label="动作类型" required>
                <ARadio.Group
                  value={action.actionTypeName}
                  onChange={e => updateActionRule(action.id, 'actionTypeName', e.target.value)}
                >
                  {actionTypeOptions.map(option => (
                    <ARadio key={option.value} value={option.value}>
                      {option.label}
                    </ARadio>
                  ))}
                </ARadio.Group>
              </AForm.Item>

              {renderActionForm(action)}
            </ACard>
          ))}

          <AButton type="dashed" icon={<PlusOutlined />} onClick={addActionRule} className="w-full">
            增加执行动作
          </AButton>
        </div>
      </AForm>
    </ADrawer>
  );
};

export default EditActionRulesDrawer;
